import {
  getStorageToken,
  setStorageToken,
  removeStorageToken,
} from "@/utils/auth";
import { tokenKey } from "@/utils/constant";
import { getRedirectToUrl } from "@/utils/util";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

import * as user from "../../service/user";

// 注册
export const fetchRegisterAction = createAsyncThunk(
  "fetchRegister",
  async (payload, { dispatch }) => {
    try {
      let res = await user.register(payload);
      return res;
    } catch (error) {
      return "err";
    }
  }
);
export const fetchLoginAction = createAsyncThunk(
  "fetchLogin",
  async (payload, { dispatch, state }) => {
    try {
      let res = await user.login(payload);
      dispatch(setToken(res.data.token));
      dispatch(fetchInfoAction());
      return res;
    } catch (error) {
      return "err";
    }
  }
);
export const fetchInfoAction = createAsyncThunk(
  "fetchInfo",
  async (payload, { dispatch }) => {
    try {
      let res = await user.getInfo();
      dispatch(setUserInfo(res.data));
      return res;
    } catch (error) {
      return "err";
    }
  }
);
export const fetchUpdateAction = createAsyncThunk(
  "fetchUpdate",
  async (payload) => {
    try {
      let res = await user.update(payload);
      return res.data;
    } catch (error) {
      return "err";
    }
  }
);
export const fetchListAction = createAsyncThunk("fetchList", async (data) => {
  let res = await user.getlist();
  return res.data;
});

let initState = {
  // 用于完善信息跳转
  redirectTo: "",
  token: getStorageToken(),
  user: "",
  role: "",
  type: "",
  money: "",
  title: "",
  avatar: "",
  _id: "",
  desc: "",
  company: "",
};
const userSlice = createSlice({
  name: "user",
  initialState: JSON.parse(JSON.stringify(initState)),
  reducers: {
    setToken(state, { payload }) {
      state.token = payload;
      setStorageToken(payload);
    },
    setUserInfo(state, { payload }) {
      Object.keys(payload).forEach((item) => {
        state[item] = payload[item];
      });
      state.redirectTo = getRedirectToUrl(payload.type);
      state.role = payload.type;
    },
    setRole(state, { payload }) {
      state.role = payload;
    },
    logout(state, { payload }) {
      Object.keys(initState).forEach((key) => {
        state[key] = initState[key];
      });
      state.token = "";
      removeStorageToken(tokenKey);
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchLoginAction.fulfilled, (state, { payload }) => {});
    builder.addCase(fetchInfoAction.fulfilled, (state, { payload }) => {});
  },
});
export const { setToken, setUserInfo, setRole, logout } = userSlice.actions;
export default userSlice.reducer;
